<template>
    <div>
        <el-container style="height: 900px; border: 1px solid #eee">
            <el-header style="font-size: 40px; background-color: rgb(238, 241, 246)">
                <div class="header-left">
                    <span>书缘校园-校园二手书交流系统</span>
                </div>
                <div class="header-right">
                    <router-link to="/mySetting">
                        <el-avatar
                            src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
                    </router-link>
                </div>
            </el-header>
            <el-container>
                <aside-layout></aside-layout>
                <el-main>
                    <el-row type="flex" justify="space-between">
                        <el-col :span="12">
                            <el-input placeholder="请输入内容" v-model="searchQuery" style="width: 350px;">
                                <el-button slot="append" icon="el-icon-search"></el-button>
                            </el-input>
                        </el-col>
                        <el-col :span="6" class="text-right">
                            <el-button type="primary" @click="goToPost">发布帖子</el-button>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-card class="post-list-card">
                                <el-card v-for="post in displayedPosts" :key="post.id" class="post-card">
                                    <div slot="header" class="clearfix">
                                        <span>{{ post.title }}</span>
                                        <el-button style="float: right; padding: 3px 0" type="text"
                                            @click="viewPost(post.id)">查看详情</el-button>
                                    </div>
                                    <div class="post-content">{{ post.content }}</div>
                                    <div class="post-footer">
                                        <!-- 点赞按钮 -->
                                        <el-button type="text" icon="el-icon-thumb" :class="{ 'liked': post.hasLiked }"
                                            @click="toggleLike(post)">
                                            {{ post.hasLiked ? '取消点赞' : '点赞' }}
                                        </el-button>

                                        <span>{{ post.likes }} 次点赞</span>

                                        <el-button type="text" icon="el-icon-star-off"
                                            :class="{ 'favorited': post.hasFavorited }" @click="toggleFavorite(post)">
                                            {{ post.hasFavorited ? '取消收藏' : '收藏' }}
                                        </el-button>

                                        <span>{{ post.favorites }} 次收藏</span>
                                    </div>
                                </el-card>
                            </el-card>
                        </el-col>
                    </el-row>
                </el-main>
            </el-container>
        </el-container>
    </div>
</template>

<script>
import axios from "axios";
import AsideLayout from '../../layout/AsideLayout.vue';
export default {
    components: { AsideLayout },
    data() {
        return {
            searchQuery: '', // 搜索关键词
            posts: [], // 帖子列表
            likedPosts: JSON.parse(localStorage.getItem('likedPosts')) || [], // 存储当前用户已点赞的帖子 ID 列表
            favoritedPosts: JSON.parse(localStorage.getItem('favoritedPosts')) || [], // 存储当前用户已收藏的帖子 ID 列表
        };
    },
    computed: {
        displayedPosts() {
            console.log('Displayed Posts:', this.posts); // 打印显示的帖子数据
            return this.posts.map(post => ({
                ...post,
                hasLiked: this.likedPosts.includes(post.id), // 判断当前帖子是否被用户点赞
                hasFavorited: this.favoritedPosts.includes(post.id), // 判断当前帖子是否被用户收藏
            }));
        }
    },
    methods: {
        getToken() {
            // 获取JWT令牌，通常保存在localStorage或sessionStorage中
            return localStorage.getItem('token'); // 这里的 token 假设存储在 localStorage 中
        },

        // 配置请求的 headers，携带 JWT 令牌
        configureHeaders() {
            const token = this.getToken();
            return {
                headers: {
                    Authorization: `Bearer ${token}`,  // 添加 Authorization 头部
                }
            };
        },

        // 获取最新的帖子列表
        async fetchPosts() {
            try {
                const res = await axios.get('http://localhost:3000/api/community/posts', this.configureHeaders());
                if (Array.isArray(res.data.posts)) {
                    this.posts = res.data.posts;
                    this.likedPosts = res.data.likedPosts || [];
                    this.favoritedPosts = res.data.favoritedPosts || [];
                    // 持久化存储点赞和收藏状态
                    localStorage.setItem('likedPosts', JSON.stringify(this.likedPosts));
                    localStorage.setItem('favoritedPosts', JSON.stringify(this.favoritedPosts));
                }
            } catch (err) {
                console.error('获取帖子失败:', err);
                this.$message.error('获取帖子失败');
            }
        },

        // 点赞或取消点赞
        async toggleLike(post) {
            const postId = post.id;
            try {
                if (this.likedPosts.includes(postId)) {
                    // 取消点赞
                    await axios.post(`http://localhost:3000/api/community/posts/${postId}/unlike`, {}, this.configureHeaders());
                    this.likedPosts = this.likedPosts.filter(id => id !== postId); // 移除已点赞的帖子 ID
                    post.likes -= 1;
                    post.hasLiked = false;
                    this.$message.success('取消点赞成功');
                } else {
                    // 点赞
                    await axios.post(`http://localhost:3000/api/community/posts/${postId}/like`, {}, this.configureHeaders());
                    this.likedPosts.push(postId); // 添加已点赞的帖子 ID
                    post.likes += 1;
                    post.hasLiked = true;
                    this.$message.success('点赞成功');
                }

                // 持久化存储点赞状态
                localStorage.setItem('likedPosts', JSON.stringify(this.likedPosts));
            } catch (err) {
                console.error('点赞失败:', err);
                this.$message.error('点赞失败');
            }
        },

        // 收藏或取消收藏
        async toggleFavorite(post) {
            const postId = post.id;
            try {
                if (this.favoritedPosts.includes(postId)) {
                    // 取消收藏
                    await axios.post(`http://localhost:3000/api/community/posts/${postId}/unfavorite`, {}, this.configureHeaders());
                    this.favoritedPosts = this.favoritedPosts.filter(id => id !== postId); // 移除已收藏的帖子 ID
                    post.favorites -= 1;
                    post.hasFavorited = false;
                    this.$message.success('取消收藏成功');
                } else {
                    // 收藏
                    await axios.post(`http://localhost:3000/api/community/posts/${postId}/favorite`, {}, this.configureHeaders());
                    this.favoritedPosts.push(postId); // 添加已收藏的帖子 ID
                    post.favorites += 1;
                    post.hasFavorited = true;
                    this.$message.success('收藏成功');
                }

                // 持久化存储收藏状态
                localStorage.setItem('favoritedPosts', JSON.stringify(this.favoritedPosts));
            } catch (err) {
                console.error('收藏失败:', err);
                this.$message.error('收藏失败');
            }
        }
    },

    // 页面刷新时，重新获取数据
    created() {
        this.fetchPosts(); // 组件创建时加载帖子数据
    }
};
</script>

<style>
.el-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left {
  font-weight: bold;
}

.post-card {
    margin-bottom: 20px;
}

.post-content {
    margin-bottom: 10px;
}

.post-footer {
    text-align: right;
}

.post-list-card {
    border: 1px solid #e0e0e0;
    padding: 20px;
    margin-bottom: 20px;
}

.text-center {
    text-align: center;
}

.liked {
    color: #f56c6c;
    /* 点赞时变为红色 */
}

.favorited {
    color: #f39c12;
    /* 收藏时变为黄色 */
}
</style>